
import Vue from 'vue'
import Vuex from 'vuex'
import { loginAPI } from '../api/login'
import Storage from './../utils/storage'

Vue.use(Vuex)

export default new Vuex.Store({
  strict: true,
  state: {
    token: Storage.get('tokenStr') || '',
    refresh_token: Storage.get('refreshTokenStr') || '',
    userInfo: {
      name: '',
      photo: Storage.get('photo')
    }
  },
  mutations: {
    setToken (state, tokenStr) {
      state.token = tokenStr
      localStorage.setItem('tokenStr', tokenStr)
    },
    setRefreshToken (state, refreshTokenStr) {
      state.refresh_token = refreshTokenStr
      localStorage.setItem('refreshTokenStr', refreshTokenStr)
    },
    setUserInfo (state, userObj) {
      state.userInfo = userObj
    },
    setUserName (state, val) {
      state.userInfo.name = val
    },
    setUser (state, userObj) {
      state.userInfo.photo = userObj
      localStorage.setItem('photo', userObj)
    }
  },
  actions: {
    async asyncLoginAction (store, formLogin) {
      const res = await loginAPI(formLogin)
      const { token, refresh_token: refreshToken } = res.data
      store.commit('setToken', token)
      store.commit('setRefreshToken', refreshToken)
    }
  },
  modules: {
  }
})
